import { computed } from 'vue';
import Icon from '../../icon/icon.vue';

export const useTabs = (props, attrs) => {
  /**
   * @description 计算Tabs属性
   * @return {Object} TabValues
   */
  const getTabValues = computed(() => {
    return { ...attrs, animated: props.animated };
  });

  /**
   * @description 计算Pane属性
   * @return {Object} PaneValues
   */
  const getPaneValues = computed(() => {
    const curIndex = props.tabList.findIndex(item => item.name === attrs.modelValue && item.saved);

    return (tab, index) => {
      const { saved, name } = tab;
      let clickFlag = true;
      if (index > 1) {
        clickFlag = curIndex + 1 === index || props.tabList[index - 1].saved;
      }

      return {
        name,
        label: generateTabLabel(tab),
        disabled: props.verify ? (clickFlag ? false : !saved) : false,
      };
    };
  });

  /**
   * @description TabLabel的render
   * @param {Object} tabItem
   * @return {Object} renderFn
   */
  const generateTabLabel = tab => {
    const { label, saved } = tab;
    const { hasIcon } = props;

    return h => {
      return h('div', { class: 'ivu-tabs-tab-label' }, [
        h(
          'span',
          {
            class: saved ? 'saved' : '',
          },
          label
        ),
        hasIcon
          ? h(Icon, {
              type: tab.icon ? tab.icon : 'md-checkmark-circle-outline',
              size: attrs.size === 'small' ? 16 : 20,
              class: saved ? 'saved' : '',
            })
          : '',
      ]);
    };
  };

  return {
    getTabValues,
    getPaneValues,
  };
};
